package yl.hs.bmipfull.controllers.home;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import yl.hs.bmipfull.controllers.ControllerBase;
import yl.hs.bmipfull.pojo.system.AppSettingEntity;
import yl.hs.bmipfull.pojo.system.WechatUserEntity;
import yl.hs.bmipfull.service.material.*;
import yl.hs.bmipfull.service.production.IProductionTaskService;
import yl.hs.bmipfull.service.salemanage.ICustomerInfoService;
import yl.hs.bmipfull.service.salemanage.ISaleContractProductsService;
import yl.hs.bmipfull.service.salemanage.ISaleContractService;
import yl.hs.bmipfull.service.system.IAppSettingService;
import yl.hs.bmipfull.service.system.IWechatUserService;
import yl.hs.bmipfull.service.vehiclemanage.ITruckInfoService;
import yl.hs.bmipfull.utils.CK;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.Mqtt.MqttConsumerConfig;
import yl.hs.bmipfull.viewmodels.SubmitModel;
import yl.hs.bmipfull.viewmodels.WebResult;

/**
 * 作用:   <br/>
 * 创建时间: 2022-08-12 08:50 <br/>
 * 无人值守司机注册相关操作控制层
 *
 * @author 吴高丰
 */
@Api(value = "无人值守司机注册相关操作控制层", tags = "无人磅房系统——无人值守司机注册相关操作控制层")
@RequestMapping("/registration")
@RestController
public class DriverRegistrationController extends ControllerBase {
    @Autowired
    ISupplierService supplierService;
    @Autowired
    IPurchaseContractService purchaseContractServiceservice;
    @Autowired
    IPurchaseContractProductService purchaseContractProductService;
    @Autowired
    IPurchaseReceiptService purchaseReceiptServiceservice;
    @Autowired
    IRawMaterialInventoryService service;
    @Autowired
    ITruckInfoService truckInfoService;
    @Autowired
    IWechatUserService wechatUserService;
    @Autowired
    ISaleContractService saleContractService;
    @Autowired
    ISaleContractProductsService saleContractProductsService;
    @Autowired
    ICustomerInfoService customerInfoService;
    @Autowired
    IProductionTaskService taskService;
    @Autowired
    IAppSettingService appSettingService;

    @ApiOperation(value = "查询全部供应商信息", tags = "查询全部供应商信息")
    @RequestMapping(value = "queryallsupplier", method = RequestMethod.GET)
    public WebResult queryAllSupper() {
        try {
            var suppliers = supplierService.queryListAll();
            return success("查询成功", suppliers);
        } catch (Exception ee) {
            return fail("查询失败");
        }
    }

    @ApiOperation(value = "查询供应商合同信息", notes = "查询所有原材分类信息")
    @RequestMapping(value = "/querycontract/{supplierSN}", method = RequestMethod.GET)
    public WebResult GetSupperContract(@PathVariable String supplierSN) {
        var result = purchaseContractServiceservice.querySupplierSn(supplierSN).stream().filter(s->s.getState()<=3).toList();
        if (result != null && result.size() > 0) {
            return success("查询成功", result.get(0));
        }
        return success("未找到数据");
    }

    @ApiOperation(value = "查询供应商原材信息", notes = "查询供应商原材信息")
    @RequestMapping(value = "/querymaterials/{supplierSN}", method = RequestMethod.GET)
    public WebResult quesyPurchaseContractbySupplierSN(@ApiParam(value = "供应商编号") @PathVariable String supplierSN) {
        try {
            var result = purchaseContractServiceservice.querySupplierSn(supplierSN).stream().filter(s->s.getState()<=3).toList();
            if (result != null && result.size() > 0) {
                var controct = purchaseContractProductService.queryListByContractSn(result.get(0).getSn()).stream().filter(s -> Integer.parseInt(String.valueOf(s.get("state"))) >= 0);
                return success("查询成功", controct);
            }
            return success("未找到数据");
        } catch (Exception ee) {
            return fail("查询失败");
        }
    }

    @ApiOperation(value = "查询原材对应仓库信息", notes = "查询原材对应仓库信息")
    @RequestMapping(value = "/byrawsn/{sn}", method = RequestMethod.GET)
    public WebResult findByRawSn(@ApiParam(value = "编号") @PathVariable String sn) {
        return success("查询成功", service.findByRawSn(sn));
    }

    @ApiOperation(value = "根据微信用户openid获取注册信息", notes = "根据微信用户openid获取注册信息")
    @RequestMapping(value = "/byopenid/{openid}", method = RequestMethod.GET)
    public WebResult findWeCharUser(@PathVariable String openid) {
        var user = wechatUserService.findByOpenId(openid);
        if (user != null) {
            return success("查询成功", user);
        } else {
            return success("未找到注册信息");
        }
    }

    @ApiOperation(value = "保存微信注册用户信息", notes = "查询/更新微信注册用户信息信息")
    @RequestMapping(value = {"/save/{truckplate}", "/save/{truckplate}/{companyid}"}, method = RequestMethod.PUT)
    public WebResult saveWechatUser(@ApiParam(value = "提交信息") @RequestBody WechatUserEntity submitModel, @PathVariable String truckplate, @PathVariable(required = false) String companyid) {
        Integer result;
        try {
            var map = submitModel.toMap();
            map.remove("id");
            result = wechatUserService.saveWechatUser(map, submitModel.getId(), truckplate, companyid);
            if (result == 1) {
                return success("保存成功");
            } else if (result == 2) {
                return success("开票限额，请注意");
            } else if (result == -10) {
                return fail("合同余额不足,已禁止发货！");
            } else if (result == -20) {
                return fail("车牌号不合规，请重新填写");
            } else {
                return fail("数据未保存");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
            return fail("数据未保存");
        }
    }

    @ApiOperation(value = "查询执行中的合同信息", notes = "查询执行中的合同信息")
    @RequestMapping(value = "/getSaleContract/{type}", method = RequestMethod.GET)
    public WebResult getSaleContract(@PathVariable int type) {
        try {
            //type:1石粉提货，3骨料提货，
            String productCateSN = "";
            AppSettingEntity appSetting = null;
            if (type == 1) {
                appSetting = appSettingService.getByParamCode(CK.SaleRawMatailSN);
            } else if (type == 3) {
                appSetting = appSettingService.getByParamCode(CK.AggregateTakeoutSN);
            }
            if (appSetting != null) {
                productCateSN = appSetting.getParamValue();
            }
            String finalProductCateSN = productCateSN;
            var salecontract = saleContractService.queryList().stream().filter(t -> t.getState() == 2 && finalProductCateSN.equals(t.getProductCateSN())).toList();
            return success("查询成功", salecontract);
        } catch (Exception ee) {
            return fail("系统错误");
        }
    }

    @ApiOperation(value = "根据客户编号查询客户信息", notes = "根据客户编号查询客户信息")
    @RequestMapping(value = "/getcustomer/{sn}", method = RequestMethod.GET)
    public WebResult getCustomer(@PathVariable String sn) {
        try {
            var customer = customerInfoService.findBySN(sn);
            return success("查询成功", customer);
        } catch (Exception ee) {
            return fail("系统错误");
        }
    }

    @ApiOperation(value = "查询执行中的合同信息产品信息", notes = "查询执行中的合同信息产品信息")
    @RequestMapping(value = "/getSaleContractproduct/{salecontractsn}", method = RequestMethod.GET)
    public WebResult getSaleContractProduct(@PathVariable String salecontractsn) {
        try {
            var prouduct = saleContractProductsService.getSaleContractProductCateName(salecontractsn);
            return success("查询成功", prouduct);
        } catch (Exception ee) {
            return fail("系统错误");
        }
    }

    @ApiOperation(value = "查询生产中的沥青生产任务", notes = "查询生产中的沥青生产任务")
    @RequestMapping(value = "/getProducttasklq", method = RequestMethod.GET)
    public WebResult GetProductTask() {
        var appSetting = appSettingService.getByParamCode(CK.lqcpsn);
        String cateSN = "";
        if (appSetting != null) {
            cateSN = appSetting.getParamValue();
        }
        var task = taskService.queryTaskSc(cateSN);
        return success("查询成功", task);
    }

    /**
     * 测试通过MQTT协议发布主题
     */
    @Autowired
    private MqttConsumerConfig mqttConsumerConfig;

    @RequestMapping("/sendMessage")
    @ResponseBody
    public WebResult sendMessage(int qos, boolean retained, String topic, String message) {
        try {
            mqttConsumerConfig.publish(qos, retained, topic, message);
            return success("发送成功");
        } catch (Exception e) {
            return error(e);
        }
    }
}
